package org.example.demo1.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.demo1.dto.*;
import org.example.demo1.service.SSHTerminalService;
import org.example.demo1.service.SmartTerminalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/terminal")
@Slf4j
@CrossOrigin(origins = "*")
public class TerminalController {

    @Autowired
    private SSHTerminalService sshTerminalService;

    @Autowired
    private SmartTerminalService smartTerminalService;

    // ============ SSH终端相关接口 ============

    /**
     * 测试SSH连接
     */
    @PostMapping("/ssh/test-connection")
    public ResponseEntity<SSHConnectionResult> testSSHConnection(@RequestBody SSHConnectionRequest request) {
        try {
            log.info("测试SSH连接: {}@{}:{}", request.getUsername(), request.getHost(), request.getPort());

            String testSessionId = "test_" + System.currentTimeMillis();

            boolean connected = sshTerminalService.connectSSH(
                    testSessionId,
                    request.getHost(),
                    request.getPort(),
                    request.getUsername(),
                    request.getPassword()
            );

            SSHConnectionResult result = new SSHConnectionResult();
            result.setSuccess(connected);

            if (connected) {
                result.setMessage("SSH连接测试成功");
                result.setHost(request.getHost());
                result.setPort(request.getPort());
                result.setUsername(request.getUsername());

                sshTerminalService.disconnectSSH(testSessionId);
            } else {
                result.setMessage("SSH连接测试失败，请检查连接信息");
            }

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("SSH连接测试失败", e);

            SSHConnectionResult result = new SSHConnectionResult();
            result.setSuccess(false);
            result.setMessage("连接测试异常: " + e.getMessage());

            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取SSH连接状态
     */
    @GetMapping("/ssh/connection-status/{sessionId}")
    public ResponseEntity<Map<String, Object>> getConnectionStatus(@PathVariable String sessionId) {
        try {
            boolean connected = sshTerminalService.isConnected(sessionId);

            Map<String, Object> result = new HashMap<>();
            result.put("connected", connected);
            result.put("sessionId", sessionId);

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("获取连接状态失败", e);

            Map<String, Object> result = new HashMap<>();
            result.put("connected", false);
            result.put("error", e.getMessage());

            return ResponseEntity.ok(result);
        }
    }

    // ============ 智能终端相关接口 ============

    /**
     * 解析自然语言为命令
     */
    @PostMapping("/parse-command")
    public ResponseEntity<CommandParseResult> parseCommand(@RequestBody CommandParseRequest request) {
        try {
            log.info("收到命令解析请求: {}", request.getInput());

            CommandParseResult result = smartTerminalService.parseNaturalLanguage(
                    request.getInput(),
                    request.getCluster(),
                    request.getNamespace()
            );

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("命令解析失败", e);
            return ResponseEntity.ok(CommandParseResult.error(e.getMessage()));
        }
    }

    /**
     * 执行kubectl命令
     */
    @PostMapping("/execute")
    public ResponseEntity<CommandExecutionResult> executeCommand(@RequestBody CommandExecutionRequest request) {
        try {
            log.info("执行命令: {}", request.getCommand());

            CommandExecutionResult result = smartTerminalService.executeCommand(
                    request.getCommand(),
                    request.getCluster(),
                    request.getNamespace()
            );

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("命令执行失败", e);
            return ResponseEntity.ok(CommandExecutionResult.error(e.getMessage()));
        }
    }

    // ============ 通用接口 ============

    /**
     * 获取快捷命令列表
     */
    @GetMapping("/quick-commands")
    public ResponseEntity<List<Map<String, Object>>> getQuickCommands() {
        try {
            List<Map<String, Object>> quickCommands = Arrays.asList(
                    Map.of("label", "查看Pod", "command", "kubectl get pods", "description", "查看所有Pod状态"),
                    Map.of("label", "查看节点", "command", "kubectl get nodes", "description", "查看集群节点"),
                    Map.of("label", "查看服务", "command", "kubectl get svc", "description", "查看所有服务"),
                    Map.of("label", "查看命名空间", "command", "kubectl get ns", "description", "查看所有命名空间"),
                    Map.of("label", "查看部署", "command", "kubectl get deploy", "description", "查看所有部署"),
                    Map.of("label", "清屏", "command", "clear", "description", "清空终端屏幕"),
                    Map.of("label", "查看目录", "command", "ls -la", "description", "查看当前目录文件"),
                    Map.of("label", "查看进程", "command", "ps aux", "description", "查看系统进程")
            );

            return ResponseEntity.ok(quickCommands);

        } catch (Exception e) {
            log.error("获取快捷命令失败", e);
            return ResponseEntity.status(500).body(null);
        }
    }

    /**
     * 健康检查
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> healthCheck() {
        Map<String, Object> health = new HashMap<>();
        health.put("status", "UP");
        health.put("service", "Terminal Service");
        health.put("timestamp", System.currentTimeMillis());

        return ResponseEntity.ok(health);
    }
}
